package com.example.springsecurity.security;

import org.springframework.security.core.Authentication;

/**
 * @author wuancheng
 * @date 2024/6/20 10:12
 * @description ThreadLocal保存当前线程登录的用户信息（记得销毁，否则会导致内存泄露）
 */
public class AuthenticationThreadLocal {

    private static final ThreadLocal<Authentication> contextHolder = new ThreadLocal<>();

    /**
     * 获取ThreadLocal存储数据
     *
     * @return
     */
    public static Authentication getContext() {
        return contextHolder.get();
    }

    /**
     * 保存ThreadLocal数据
     *
     * @param context
     */
    public static void setContext(Authentication context) {
        contextHolder.set(context);
    }

    /**
     * 清除ThreadLocal
     */
    public static void clearContext() {
        contextHolder.remove();
    }
}
